<template>
  <div>
    <el-upload
      ref="uploadSingleImg"
      :action="uploadFileUrl"
      name="file"
      :data="data"
      :auto-upload="false"
      list-type="picture-card"
      :limit="1"
      :on-success="handleSuccess"
      :on-preview="handlePictureCardPreview"
      :on-exceed="handleExceed"
      :on-change="handleChange"
      :on-remove="handleRemove"
    >
      <i class="el-icon-plus" />
    </el-upload>

    <el-dialog
      width="30%"
      title="图片"
      :visible.sync="imgView"
      append-to-body
      center
    >
      <el-image :src="imgUrl" />
    </el-dialog>
  </div>
</template>

<script>
import store from '@/store'

export default {
  name: 'UploadSingleImg',
  props: {
    imageFileName: {
      type: String,
      required: true
    },
    temp: {
      type: Object,
      required: true
    },
    submit: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      uploadFileUrl: store.getters.uploadFileUrl,
      data: {
        account: store.getters.token,
        path: this.imageFileName
      },
      imgUrl: '',
      imgView: false
    }
  },
  watch: {
    submit(newValue, oldValue) {
      if (newValue === 'submit') {
        this.$refs['uploadSingleImg'].submit()
      }
    }
  },
  methods: {
    handleSuccess(response, file, fileList) {
      fileList.pop()
      this.temp.image = response.fileName
      this.$emit('upload-success')
    },
    handlePictureCardPreview(file) {
      this.imgUrl = file.url
      this.imgView = true
    },
    handleChange(file, fileList) {
      if (this.temp.image === '') {
        this.temp.image = 'hasImage'
      }
    },
    handleRemove(file, fileList) {
      if (fileList.length === 0) {
        this.temp.image = ''
      }
    },
    handleExceed(file) {
      this.$message({
        message: '当前版本只支持上传一张图片！',
        type: 'warning'
      })
    }
  }
}
</script>

<style scoped>

</style>
